package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Race;
import model.RaceMsg;
import service.CompanyService;
import service.RaceService;
import service.impl.CompanyServiceImpl;
import service.impl.RaceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 燕子豪
 * @Date: 2022/12/17 17:11
 */
@WebServlet("/raceListByName")
public class RaceListByNameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        CompanyService companyServiceImpl = new CompanyServiceImpl();
        RaceService raceService = new RaceServiceImpl();
        //解析前端并转为json类型
        BufferedReader reader = new BufferedReader(request.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //解析前端的参数：partName、pageIndex，pageSize给定为5
        String partName = jsonObject.getString("partName");
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));

        //创建raceMsgList容器
        List<RaceMsg> raceMsgList = new ArrayList<>();
        //暂定页面大小为5
        int pageSize = 5;
        List<Race> races = raceService.findByPartName(partName, pageIndex, pageSize);
        for (Race race : races) {
            RaceMsg raceMsg = new RaceMsg();
            //填充数据
            raceMsg.setRace(race);
            raceMsg.setCompany(companyServiceImpl.selectById(race.getCid()));
            raceMsgList.add(raceMsg);
        }
        int count = raceService.countByName(partName);

        //将数据List打包为json发给前端
        JSONObject message = new JSONObject();
        message.put("racesMsg", raceMsgList);
        message.put("pageCount", count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        response.getWriter().write(message.toString());
    }
}